package com.opdar.athena.web.service;

import com.opdar.athena.base.Constants;
import com.opdar.athena.entities.ErrorResult;
import com.opdar.athena.entities.ProjectEntity;
import com.opdar.athena.mapper.ProjectMapper;
import com.opdar.platform.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;

/**
 * Created by shiju on 2017/7/10.
 */
@Service
public class AppCheckService {

    @Autowired
    ProjectMapper projectMapper;

    public ProjectEntity checkAppId(String appId){
        if(appId == null)return null;
        ProjectEntity query = new ProjectEntity();
        query.setAppId(appId);
        query = projectMapper.selectOne(query);
        return query;
    }

    public String getSign(HashMap<String,Object> parameters, String appSecret){
        TreeMap<String,Object> treeMap = new TreeMap<String, Object>();
        StringBuilder builder = new StringBuilder();
        treeMap.putAll(parameters);
        for(Iterator<String> it = treeMap.keySet().iterator(); it.hasNext();){
            String key = it.next();
            builder.append(key).append("=").append(treeMap.get(key));
        }
        builder.append(appSecret);
        return MD5.encrypt(builder.toString());
    }

    public ErrorResult authApp(HashMap<String,Object> parameters){
        String appId = (String) parameters.get("appId");
        String signature = (String) parameters.remove("signature");
        return authApp(parameters,appId,signature);
    }

    public ErrorResult authApp(HashMap<String,Object> parameters, String appId,String signature){
        if(!parameters.containsKey("appId")){
            parameters.put("appId",appId);
        }
        Long timestamp = (Long)parameters.get("timestamp");
        if(timestamp == null || appId == null || signature == null){
            return new ErrorResult(Constants.ErrorCode.APP_PARAMETER_ERROR);
        }
        ErrorResult errorResult = new ErrorResult();
        //根据appId检查该APP是否存在
        ProjectEntity projectEntity = checkAppId(appId);
        if(projectEntity == null){
            errorResult.setCode(Constants.ErrorCode.APP_NOT_EXIST);
            return errorResult;
        }
        //根据入参+appSecret开始加密获得sign
        String _signature = getSign(parameters,projectEntity.getAppSecret());
        //对比sign与传入sign是否一致
        if(!_signature.equals(signature))
        {
            errorResult.setCode(Constants.ErrorCode.SIGN_ERROR);
        }
        return errorResult;
    }
}
